package com.lyj.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lyj.mapper.JobMapper;
import com.lyj.pojo.Department;
import com.lyj.pojo.Employee;
import com.lyj.pojo.Job;
import com.lyj.pojo.LayuiPage;
import com.lyj.service.DepartmentService;
import com.lyj.service.EmployeeService;
import com.lyj.service.JobService;
import com.lyj.util.LayuiData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

@Controller
@RequestMapping("/job")
public class JobController {

    @Autowired
    private JobService jobService;

    @Autowired
    private EmployeeService employeeService;

    @RequestMapping("/list.html")
    public String toList(){
        return "jobList";
    }

    @RequestMapping("/addJob.html")
    public String toAdd(){
        return "addJob";
    }

    @RequestMapping("/list")
    public ResponseEntity list(LayuiPage layuiPage, Job job){
        PageHelper.startPage(layuiPage.getPage(),layuiPage.getLimit());
        List<Job> jobs =  jobService.findAllJob(job);
        return ResponseEntity.ok(LayuiData.toLayuiTableModel(new PageInfo(jobs)));
    }
    @RequestMapping("/update.html")
    public ModelAndView toUpdate(ModelAndView mv,Integer id){
        mv.addObject("job",jobService.findJobById(id));
        mv.setViewName("jobUpdate");
        return mv;
    }

    @RequestMapping("/update")
    public ResponseEntity update(@RequestBody Job job){
        List<Job> allJob = jobService.findAllJob(new Job());
        for (Job job1 : allJob) {
            if(job1.getName().equals(job.getName()) && job1.getId() != job.getId()){
                return ResponseEntity.ok("该职位名称已经存在");
            }
        }
        jobService.updateJobById(job);
        return ResponseEntity.ok("1");
    }

    @RequestMapping("/addJob")
    public ResponseEntity addJob(@RequestBody Job job){
        List<Job> allJob = jobService.findAllJob(new Job());
        for (Job job1 : allJob) {
            if (job1.getName().equals(job.getName())){
                return ResponseEntity.ok("1");
            }
        }
        jobService.addJob(job);
        return ResponseEntity.ok("2");
    }

    @RequestMapping("/delete/{id}")
    public ResponseEntity delete(@PathVariable Integer id){
        Employee employee = new Employee();
        employee.setJobId(id);
        List<Employee> allEmp = employeeService.findAllEmp(employee);
        if(!allEmp.isEmpty()){
            return ResponseEntity.ok("有多名员工属于该职位，不能删除");
        }
        jobService.deleteJobById(id);
        return ResponseEntity.ok("1");
    }



}
